using System.Collections.Generic;
using Ardal.MSBuildShellExtension.DomainModel.Impl;

/*
 * Copyright (c) 2007-2008, Thomas Ardal (thomasardalatgmail.com)
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 *
 * * Neither the name of Thomas Ardal nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
namespace Ardal.MSBuildShellExtension.DomainModel.API
{
    public class DomainModelFacade
    {
        private IConfigRegistryProvider configRegistryProvider;
        public IConfigRegistryProvider ConfigRegistryProvider
        {
            set { configRegistryProvider = value; }
            get
            {
                if (configRegistryProvider == null)
                {
                    return new ConfigRegistryProvider();
                }
                return configRegistryProvider;
            }
        }

        private static DomainModelFacade inst;

        public static DomainModelFacade Instance
        {
            get
            {
                if (inst == null)
                {
                    inst = new DomainModelFacade();
                }
                return inst;
            }
        }

        private DomainModelFacade()
        {
        }

        private IList<IEditor> editors;

        public IList<IEditor> Editors
        {
            get
            {
                if (editors == null)
                {
                    editors = ConfigRegistryProvider.GetEditors();
                }
                IList<IEditor> returnList = new List<IEditor>();
                foreach (IEditor editor in editors)
                {
                    if (!editor.Deleted)
                    {
                        returnList.Add(editor);
                    }
                }
                return returnList;
            }
        }

        /// <summary>
        /// Gets the IEditor currently selected as default editor
        /// </summary>
        public IEditor DefaultEditor
        {
            get
            {
                if (Editors.Count == 0)
                {
                    return null;
                }
                List<IEditor> editorsToSort = new List<IEditor>(Editors);
                editorsToSort.Sort(new SortByDefaultEditorComparer());
                return editorsToSort[0];
            }
        }

        private IList<ITarget> targets;

        public IList<ITarget> Targets
        {
            get
            {
                if (targets == null)
                {
                    targets = ConfigRegistryProvider.GetTargets();
                }
                IList<ITarget> returnList = new List<ITarget>();
                foreach (ITarget target in targets)
                {
                    if (!target.Deleted)
                    {
                        returnList.Add(target);
                    }
                }
                return returnList;
            }
        }

        private IList<IExtension> extensions;

        public IList<IExtension> Extensions
        {
            get
            {
                if (extensions == null)
                {
                    extensions = ConfigRegistryProvider.GetExtensions(Targets);
                }
                IList<IExtension> returnList = new List<IExtension>();
                foreach (IExtension extension in extensions)
                {
                    if (!extension.Deleted)
                    {
                        returnList.Add(extension);
                    }
                }
                return returnList;
            }
        }

        public void Save()
        {
            IConfigRegistryProvider config = ConfigRegistryProvider;

            //Only save editors, if editors have been fetched
            if (editors != null)
            {
                foreach (IEditor editor in editors)
                {
                    config.SaveEditor(editor);
                }
            }

            //Only save targets, if targets have been fetched
            if (targets != null)
            {
                foreach (ITarget target in targets)
                {
                    config.SaveTarget(target);
                }
            }

            //Only save extensions, if extensions have been fetched or if targets have been updated
            if (extensions != null || targets != null)
            {
                //If only targets have been loaded, load extensions to see if they should update as well
                if (extensions == null)
                {
                    extensions = ConfigRegistryProvider.GetExtensions(targets);
                }
                foreach (IExtension extension in extensions)
                {
                    config.SaveExtension(extension);
                }
            }

            UnModifyAll();
        }

        public ITarget FindTargetByTitle(string title)
        {
            foreach (ITarget t in Targets)
            {
                if (t.Title.Equals(title))
                {
                    return t;
                }
            }
            return null;
        }

        public IEditor AddEditor(string title, string filename, string arguments, bool defaultEditor)
        {
            IEditor newEditor = new Editor(title, filename, arguments, defaultEditor);
            editors.Add(newEditor);
            return newEditor;
        }

        public ITarget AddTarget(string title, string target, Verbosity verbosity, Configuration configuration, bool showErrorList)
        {
            ITarget newTarget = new Target(title, target, verbosity, configuration, showErrorList);
            targets.Add(newTarget);
            return newTarget;
        }

        public IExtension AddExtension(string fileExtension, string dotNetVersion, IList<ITarget> includededTargets)
        {
            IExtension newExtension = new Extension(fileExtension, dotNetVersion, includededTargets);
            extensions.Add(newExtension);
            return newExtension;
        }

        private void UnModifyAll()
        {
            foreach (IEditor editor in Editors)
            {
                editor.Modified = false;
            }
            foreach (ITarget target in Targets)
            {
                target.Modified = false;
            }
            foreach (IExtension extension in Extensions)
            {
                extension.Modified = false;
            }
        }

        public bool Dirty
        {
            get
            {
                foreach (IEditor editor in Editors)
                {
                    if (editor.Modified) return true;
                }
                foreach (ITarget target in Targets)
                {
                    if (target.Modified) return true;
                }
                foreach (IExtension extension in Extensions)
                {
                    if (extension.Modified) return true;
                }
                return false;
            }
        }

        public void Clear()
        {
            editors = null;
            targets = null;
            extensions = null;
        }

        /// <summary>
        /// Finds an editor by it's title. The first found editor is returned.
        /// </summary>
        /// <param name="title">The title of the wanted editor</param>
        /// <returns>The found editor. Returns null if no editor with
        /// the specified title is found.</returns>
        public IEditor FindEditorByTitle(string title)
        {
            foreach (IEditor editor in Editors)
            {
                if (editor.Title.Equals(title))
                {
                    return editor;
                }
            }
            return null;
        }
    }
}
